/*
 * Copyright @ 2014 com.iflysse.trains
 * manger_v2.0 上午8:54:03
 * All right reserved.
 *
 */
package com.iflysse.servlet.role;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iflysse.pojo.MenuInfo;
import com.iflysse.pojo.RoleInfo;
import com.iflysse.pojo.RoleMenu;
import com.iflysse.pojo.TreeJson;
import com.iflysse.service.MenuInfoService;
import com.iflysse.service.RoleInfoService;
import com.iflysse.service.RoleMenuService;
import com.iflysse.utils.PagerBean;

/**
 * @desc: manger_v2.0
 * @author: wql
 * @createTime: 2014年11月20日 上午8:54:03
 * @history:
 * @version: v1.0
 */
@WebServlet("/role/roleadmin.do")
public class RoleInfoServlet extends HttpServlet {
	private RoleInfoService service = new RoleInfoService();

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String mtd = req.getParameter("method");
		if ("load".equals(mtd)) {
			load(req, resp);
		} else if ("del".equals(mtd)) {
			delrole(req, resp);
		} else if ("initForm".equals(mtd)) {
			initForm(req, resp);
		} else if ("addForm".equals(mtd)) {
			addForm(req, resp);
		} else if ("insert".equals(mtd)) {
			insert(req, resp);
		} else if ("update".equals(mtd)) {
			update(req, resp);
		} else if ("jsontree".equals(mtd)) {
			myjosn(req, resp);
		} else if ("tijiao".equals(mtd)) {
			savePw(req, resp);
		} else {
			req.getRequestDispatcher("/WEB-INF/views/roleadmin/roleindex.jsp")
					.forward(req, resp);
		}
	}

	/**
	*
	* @author: wql
	* @createTime: 2014年11月30日 下午5:05:11
	* @history:
	* @param req
	* @param resp void
	 * @throws IOException 
	 * @throws ServletException 
	*/
	private void addForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		RoleInfo roleInfo = new RoleInfo();
		req.setAttribute("roleInfo", roleInfo);
		req.getRequestDispatcher("/WEB-INF/views/roleadmin/form.jsp").forward(
				req, resp);
	}

	public void savePw(HttpServletRequest req, HttpServletResponse resp){
		String roleid = req.getParameter("roleid");
		String menuids = req.getParameter("menuids");
//		System.out.println(roleid);
//		System.out.println(menuids);
		String[] mds = menuids.split(",");
		RoleMenuService rservice = new RoleMenuService();
		//删除原先数据库中该roleid对应的所有的菜单
		int rid = Integer.parseInt(roleid);
		rservice.deleteByRoleId(rid);
		
		
		for(int i=0;i<mds.length;i++){
			RoleMenu rm  = new RoleMenu();
			rm.setRoleid(Integer.parseInt(roleid));
			rm.setMenuid(Integer.parseInt(mds[i]));
			rservice.insertRoleMenu(rm);
		}
		
	}
	/**
	 *
	 * @author: wql
	 * @createTime: 2014年11月26日 上午9:44:03
	 * @history:
	 * @param req
	 * @param resp
	 *            void
	 */
	private void myjosn(HttpServletRequest req, HttpServletResponse resp) {

		MenuInfoService menuservice = new MenuInfoService();
		List<TreeJson> parents = LoadBigTree(menuservice);

		try {
			print2Page(resp, parents.toString());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 返回权限的最大树
	 */
	private List<TreeJson> LoadBigTree(MenuInfoService menuservice) {
		List<MenuInfo> menulist = menuservice.findAllMenu();

		List<TreeJson> parents = new ArrayList<TreeJson>();
		for (MenuInfo minfo : menulist) {
			int pid = minfo.getParentId();
			if (pid == 1) {
				TreeJson tj = new TreeJson();
				tj.setId(minfo.getMenuId());
				tj.setText(minfo.getMenuName());
				tj.setPid(pid);

				int id = minfo.getMenuId();

				List<TreeJson> childs = new ArrayList<TreeJson>();
				for (MenuInfo inf : menulist) {
					int cpid = inf.getParentId();
					if (cpid == id) {
						TreeJson ctj = new TreeJson();
						ctj.setId(inf.getMenuId());
						ctj.setText(inf.getMenuName());
						ctj.setPid(cpid);
						childs.add(ctj);
					}
				}
				tj.setChildren(childs);
				parents.add(tj);
			}

		}
		return parents;
	}

	/**
	 *
	 * @author: wql
	 * @createTime: 2014年11月20日 上午10:45:00
	 * @history:
	 * @param req
	 * @param resp
	 *            void
	 * @throws IOException
	 * @throws ServletException
	 */
	private void update(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RoleInfo role = new RoleInfo();
		role.setRoleId(Integer.parseInt(req.getParameter("roleid")));
		role.setRoleCode(req.getParameter("rolecode"));
		role.setRoleName(req.getParameter("rolename"));
		role.setRoleDescription(req.getParameter("roledescription"));
		service.updatetRole(role);
//		System.out.println("a"+role);
		resp.sendRedirect(req.getContextPath()+"/role/roleadmin.do");
	}

	/**
	 *
	 * @author: wql
	 * @createTime: 2014年11月20日 上午10:44:58
	 * @history:
	 * @param req
	 * @param resp
	 *            void
	 * @throws IOException
	 * @throws ServletException
	 */
	private void insert(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RoleInfo role = new RoleInfo();
		role.setRoleId(Integer.parseInt(req.getParameter("roleid")));
		role.setRoleCode(req.getParameter("rolecode"));
		role.setRoleName(req.getParameter("rolename"));
		role.setRoleDescription(req.getParameter("roledescription"));
		service.insertRole(role);
		resp.sendRedirect(req.getContextPath()+"/role/roleadmin.do");

	}

	/**
	 *
	 * @author: wql
	 * @createTime: 2014年11月20日 上午10:44:55
	 * @history:
	 * @param req
	 * @param resp
	 *            void
	 * @throws IOException
	 * @throws ServletException
	 */
	private void initForm(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String id = req.getParameter("roleid");
		int roleid = Integer.parseInt(id);
		RoleInfo roleInfo = null;
		if (roleid > 0) {
			roleInfo = service.findRoleById(roleid);
		} else {
			roleInfo = new RoleInfo();
		}
//		System.out.println(roleInfo);
		req.setAttribute("roleInfo", roleInfo);
		req.getRequestDispatcher("/WEB-INF/views/roleadmin/form.jsp").forward(
				req, resp);
	}

	/**
	 *
	 * @author: wql
	 * @createTime: 2014年11月20日 上午10:44:53
	 * @history:
	 * @param req
	 * @param resp
	 *            void
	 * @throws IOException
	 */
	private void delrole(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String ids = req.getParameter("roleids");
		String[] idsArr = ids.split(",");
		for (int i = 0; i < idsArr.length; i++) {
			int id = Integer.parseInt(idsArr[i]);
			service.delRoleById(id);
		}
		print2Page(resp, "{\"msg\":\"删除成功\"}");
	}

	/**
	 *
	 * @author: wql
	 * @createTime: 2014年11月20日 上午10:44:50
	 * @history:
	 * @param req
	 * @param resp
	 *            void
	 * @throws IOException
	 */
	private void load(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String search = req.getParameter("searchword");
		if (search.equals("")) {
			PagerBean<RoleInfo> pager = new PagerBean<RoleInfo>();
			int page = 1, pageSize = 10;
			String mysort = "roleid";
			String myorder = "asc";

			try {
				page = Integer.parseInt(req.getParameter("page"));
				pageSize = Integer.parseInt(req.getParameter("rows"));

				if (req.getParameter("sort") != null
						&& req.getParameter("order") != null) {
					mysort = req.getParameter("sort");
					myorder = req.getParameter("order");
				}
			} catch (NumberFormatException ex) {

			}
			pager.setMysort(mysort);
			pager.setMyorder(myorder);
			pager.setPage(page);
			pager.setPageSize(pageSize);
			pager = service.findRolePager(pager);
			print2Page(resp, pager.toString());
		} else {
			List<RoleInfo> roles = new ArrayList<RoleInfo>();
			roles = service.findRoleByName(search);
			print2Page(resp, roles.toString());
		}

	}

	/**
	 *
	 * @author: wql
	 * @createTime: 2014年11月20日 上午10:51:50
	 * @history:
	 * @param resp
	 * @param string
	 *            void
	 * @throws IOException
	 */
	private void print2Page(HttpServletResponse resp, String json)
			throws IOException {
		resp.setContentType("application/json;charset=UTF-8");
		Writer writer = resp.getWriter();
		writer.write(json);
		writer.flush();
	}

	/**
	 * 根据当前的栏目对象，获取当前栏目对象在此集合中的子栏目对象,并对源集合进行元素减少操作
	 * 
	 * @author: Rongyu
	 * @createTime: 2014年11月21日 上午8:37:47
	 * @history:
	 * @param srclist
	 * @param info
	 * @return List<RoleInfo>
	 * 
	 *         public List<RoleInfo> getChildenroleById(List<RoleInfo>
	 *         srclist,RoleInfo info) { List<RoleInfo> childenList=new
	 *         ArrayList<RoleInfo>(); for(int i=0;i<srclist.size();i++) {
	 *         if(info.getId()==srclist.get(i).getPpid()) {
	 *         childenList.add(srclist.get(i)); srclist.remove(i); i--; } }
	 *         return childenList; } public List<RoleInfo>
	 *         getDstroleOrdered(List<RoleInfo> srcList) { List<RoleInfo>
	 *         dstList=new ArrayList<RoleInfo>(); List<RoleInfo> tempList=null;
	 *         for(int i=0;i<srcList.size();i++) {
	 *         tempList=getChildenroleById(srcList,srcList.get(i));
	 *         srcList.get(i).setName("+"+srcList.get(i).getName());
	 *         dstList.add(srcList.get(i)); if(tempList.size()!=0) { for(int
	 *         j=0;j<tempList.size();j++) {
	 *         tempList.get(j).setName("&emsp;&emsp;|----"
	 *         +tempList.get(j).getName()); dstList.add(tempList.get(j)); } }
	 *         srcList.remove(i); i--; } return dstList;
	 * 
	 *         }
	 */

}
